package com.unohacha.qqj.fzdr.personal.view.activity;

import android.graphics.Canvas;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnDrawListener;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.unohacha.qqj.fzdr.R;
import com.unohacha.qqj.fzdr.util.ToastUtils;
import com.unohacha.qqj.mylibrary.base.BaseActivity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import butterknife.BindView;
import butterknife.OnClick;

import static com.tencent.smtt.sdk.TbsListener.ErrorCode.DOWNLOAD_SUCCESS;

public class ShowPdfActivity extends BaseActivity implements OnDrawListener, OnPageChangeListener, OnLoadCompleteListener {

    @BindView(R.id.common_back)
    ImageView commonBack;
    @BindView(R.id.common_title)
    TextView commonTitle;
    @BindView(R.id.common_right_image)
    ImageView commonRightImage;
    @BindView(R.id.pdfView)
    PDFView pdfView;
    private String url;
    private String title;
//    private PDFPagerAdapter adapter;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_pdf;
    }

    @Override
    protected void initView() {
        commonRightImage.setVisibility(View.INVISIBLE);
        url = getIntent().getStringExtra("url");
        title = getIntent().getStringExtra("title");
        commonTitle.setText(title);
//                     "http://huafang.unohacha.com/uploads/admin/admin_thumb/20180626/995e9185015365bfac9bc05a70963dff.pdf"
        String aaa = "http://huafang.unohacha.com/uploads/admin/admin_thumb/20180626/995e9185015365bfac9bc05a70963dff.pdf";
        downloadpdf(url);
        //创建下载任务,downloadUrl就是下载链接
//        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(aaa));
//        //指定下载路径和下载文件名
//        request.setDestinationInExternalPublicDir("/download/", aaa);
//        //获取下载管理器
//        DownloadManager downloadManager = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE);
//        //将下载任务加入下载队列，否则不会进行下载
//        downloadManager.enqueue(request);


//        String pdfName = Environment.getExternalStorageDirectory() + "/download";
//        File file = new File(aaa);

//
//        pdfView.fromAsset(aaa)
//                .pages(0, 2, 1, 3, 3, 3)
//                .defaultPage(1)
//                .showMinimap(false)
//                .enableSwipe(true)
////                .onDraw(onDrawListener)
//                .onLoad(this)
//                .onPageChange(this)
//                .load();
//        RemotePDFViewPager remotePDFViewPager = new RemotePDFViewPager(this, aaa, this);
//        adapter = new PDFPagerAdapter(this, "AdobeXMLFormsSamples.pdf");
//        remotePDFViewPager.setAdapter(adapter);
//        setContentView(remotePDFViewPager);
//        pdfView.fromFile(new File(aaa))  //pdf地址
//                .defaultPage(1)//默认页面
//                .enableDoubletap(true)
//                .swipeHorizontal(true)//是不是横向查看
//                .onPageChange(this)
//                .enableSwipe(true)
//                .load();
    }

    private File file1;

    private void downloadpdf(final String Strname) {
        showLoading();
        //截取最后14位 作为文件名
        String s = Strname.substring(Strname.length() - 14);
        //文件存储
        file1 = new File(Environment.getExternalStorageDirectory(), getFileName(s));
        new Thread() {
            public void run() {


//              本地没有此文件 则从网上下载打开
                File downloadfile = downLoad(Strname, file1.getAbsolutePath());
//              Log.i("Log",file1.getAbsolutePath());
                Message msg = Message.obtain();
                if (downloadfile != null) {
                    // 下载成功,安装....
                    msg.obj = downloadfile;
                    msg.what = DOWNLOAD_SUCCESS;
                } else {
                    hideLoading();
//                    ToastUtils.showT("下载失败");
                    // 提示用户下载失败.
//                    msg.what = DOWNLOAD_ERROR;
                }
                handler.sendMessage(msg);
//                mProgressDialog.dismiss();
            }

            ;
        }.start();
    }

    /**
     * 下载完成后  直接打开文件
     */
    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case DOWNLOAD_SUCCESS:
                    File file = (File) msg.obj;
                    Uri uri = Uri.fromFile(file);
                    pdfView.fromUri(uri)
                            .defaultPage(0)
                            .enableDoubletap(true)
                            .onDraw(ShowPdfActivity.this)
                            .onPageChange(ShowPdfActivity.this)
                            .enableAnnotationRendering(true)
                            .onLoad(ShowPdfActivity.this)
                            .enableDoubletap(true)
                            .swipeVertical(true)
                            .load();
                    hideLoading();
            }
        }
    };
/**
 *
 */


    /**
     * 传入文件 url  文件路径  和 弹出的dialog  进行 下载文档
     */
    public static File downLoad(String serverpath, String savedfilepath) {
        try {
            URL url = new URL(serverpath);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            if (conn.getResponseCode() == 200) {
                int max = conn.getContentLength();
//                pd.setMax(max);
                InputStream is = conn.getInputStream();
                File file = new File(savedfilepath);
                FileOutputStream fos = new FileOutputStream(file);
                int len = 0;
                byte[] buffer = new byte[1024];
                int total = 0;
                while ((len = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, len);
                    total += len;
//                    pd.setProgress(total);
                }
                fos.flush();
                fos.close();
                is.close();
                return file;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    public static String getFileName(String serverurl) {
        return serverurl.substring(serverurl.lastIndexOf("/") + 1);
    }

    @OnClick(R.id.common_back)
    public void onViewClicked() {
        finish();
    }

    @Override
    public void onLayerDrawn(Canvas canvas, float pageWidth, float pageHeight, int displayedPage) {

    }

    @Override
    public void onPageChanged(int page, int pageCount) {

    }

    @Override
    public void loadComplete(int nbPages) {

    }

}
